from rest_framework import serializers
from .models import *
class PlatformSerializer(serializers.ModelSerializer):
    """
    平台序列化器
    """

    class Meta:
        model = Platefrom
        fields = "__all__"

    def create(self, validated_data):
        exist = Platefrom.objects.filter(name=validated_data['name']).exists()
        if exist:
            raise serializers.ValidationError('已存在')
        instance = Platefrom.objects.create(**validated_data)
        return instance


class PlatformAllSerializer(serializers.ModelSerializer):
    """
    平台序列化器
    """

    class Meta:
        model = Platefrom
        fields = "__all__"


class SkusSerializer(serializers.ModelSerializer):
    """套餐管理"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


    class Meta:
        model = Skus
        fields = ('id', 'title', 'labels',
                  "content_type_ids",'limit_count','price',"platefrom_ids",
                  'status', 'order','item_price','discount')

    def create(self, validated_data):
        # content_type_id = list(validated_data.pop("content_type_id", ''))
        # platform_id = list(validated_data.pop("platform", ''))
        #
        instance = Skus.objects.create(**validated_data)
        # if content_type_id:
        #     instance.content_type.add(*content_type_id)
        # if platform_id:
        #     instance.platform.add(*platform_id)
        return instance

    def update(self, instance, validated_data):
        Skus.objects.filter(pk=instance.pk).update(**validated_data)
        return instance







class SkusBindSerializer(serializers.ModelSerializer):
    """规格-用户绑定管理"""

    class Meta:
        model = SkusUser
        fields = ('id','add_time','user_id','username','title','skus_id','balance_times','company_name','company_id','type','company_id')

    def create(self, validated_data):

        # 查询可用条数
        skus_item = Skus.objects.filter(id=validated_data['skus_id']).first()
        validated_data['balance_times'] = skus_item.limit_count
        instance = SkusUser.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        # 查询新的规格
        limit_count = Skus.objects.filter(id=validated_data['skus_id']).first()
        # 新 + 旧
        if limit_count:
            new_balance_times = int(limit_count.limit_count) + int(instance.balance_times)
            validated_data['balance_times'] = new_balance_times
        else:
            validated_data['balance_times'] = int(instance.balance_times)

        # 更新
        SkusUser.objects.filter(pk=instance.pk).update(**validated_data)

        return instance